package com.fla.puzzle;

import java.util.Iterator;
import java.util.List;

import com.fla.puzzle.pack.Pack;
import com.fla.puzzle.pack.PackItem;
import com.fla.puzzle.utils.Utils;
import com.fla.puzzle.utils.Utils.Predicate;

/**
 * Provides access to available in this application game packages - {@link Pack}
 */
public class PackManager {
    private final List<Pack> packs;

    public PackManager(PackDataProvider packDataProvider) {
        this.packs = packDataProvider.loadPacks();
    }

    /**
     * Obtains next puzzle from the package with the given packId followed after packId
     * 
     * @param packId String package id
     * @param packItemId String package item id
     * @return {@link PackItem} next PackItem
     */
    public PackItem getNextPackItem(String packId, String packItemId) {
        Pack pack = getPackById(packId);
        return pack == null ? null : getNextPackItemAfterId(pack, packItemId);
    }

    public List<Pack> getAll() {
        return packs;
    }

    public Pack getPackById(final String id) {
        List<Pack> filtered = Utils.filter(packs, new Predicate<Pack>() {
            @Override
            public boolean evaluate(Pack pack) {
                return id.equals(pack.getId());
            }
        });

        return filtered.isEmpty() ? null : filtered.get(0);
    }

    private PackItem getNextPackItemAfterId(final Pack pack, final String packItemId) {
        Iterator<PackItem> packItemIterator = pack.getPackItems().iterator();
        while (packItemIterator.hasNext()) {
            PackItem packItem = packItemIterator.next();
            if (packItemId.equals(packItem.getId())) {
                return packItemIterator.hasNext() ? packItemIterator.next() : null;
            }
        }
        return null;
    }
}
